package de.pharmacontrol.psa.controller;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.server.JCoServerState;

import de.pharmacontrol.pilot.entities.Order;
import de.pharmacontrol.psa.beans.interfaces.JCoBean;
import de.pharmacontrol.psa.beans.interfaces.LoggerService;
import de.pharmacontrol.psa.beans.interfaces.OrderService;
import de.pharmacontrol.rfcserver.handler.CreateOrderFunctionHandler;
import de.pharmacontrol.rfcserver.handler.DeleteOrderFunctionHandler;
import de.pharmacontrol.rfcserver.handler.GetOrderStatusFunctionHandler;

@ManagedBean
public class RfcStatusController {

	@EJB
	LoggerService logger;

	@EJB
	JCoBean jcoBean;

	@EJB
	OrderService orderBean;

	@EJB
	CreateOrderFunctionHandler createOrderBean;

	@EJB
	DeleteOrderFunctionHandler deleteOrderBean;

	@EJB
	GetOrderStatusFunctionHandler statusOrderBean;
	
	public void restartRfc(ActionEvent actionEvent) {
		jcoBean.shutdown();
		try {
			jcoBean.connect();
		} catch (JCoException e) {
			e.printStackTrace();
		}

		getStatus(actionEvent);
	}

	public void stopRfc(ActionEvent actionEvent) {
		jcoBean.shutdown();
		getStatus(actionEvent);
	}

	public void getStatus(ActionEvent actionEvent) {
		FacesMessage fm;
		if (jcoBean.getState() == JCoServerState.STARTED) {
			fm = new FacesMessage(FacesMessage.SEVERITY_INFO, "STARTED", "RFC Server " + jcoBean.getServerName() + " is started (" + new Date() + ")");
		} else if (jcoBean.getState() == JCoServerState.STOPPED) {
			fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "STOPPED", "RFC Server " + jcoBean.getServerName() + " is stopped (" + new Date() + ")");
		} else if (jcoBean.getState() == JCoServerState.STOPPING) {
			fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "STOPPING", "RFC Server " + jcoBean.getServerName() + " is stopping (" + new Date() + ")");
		} else if (jcoBean.getState() == JCoServerState.ALIVE) {
			fm = new FacesMessage(FacesMessage.SEVERITY_INFO, "ALIVE", "RFC Server " + jcoBean.getServerName() + " is running (" + new Date() + ")");
		} else {
			fm = new FacesMessage(FacesMessage.SEVERITY_FATAL, "DEAD", "RFC Server " + jcoBean.getServerName() + " can not connect to repository (" + new Date() + ")");
		}
		logger.info("RFC status request: " + fm.getDetail());
		FacesContext.getCurrentInstance().addMessage(null, fm);
	}

	private static int createDemoOrderInt = 0;
	private static int deleteDemoOrderInt = 0;
	private static int statusDemoOrderInt = 0;
	
	public void createDemoOrder(ActionEvent actionEvent) {
		String xml = "<Z_PPFM_PCE_ORDER_CREATE><INPUT>"
				+ "<I_ORDER_CREATE><ODERNR>DEMO_ORDER_"
				+ createDemoOrderInt
				+ "</ODERNR><ACTION>1</ACTION><RESSOURCE>DMT</RESSOURCE><LAYOUT>TEST</LAYOUT><MATNR>000000000000101701</MATNR><MAKTX>HALLO PCE</MAKTX><CHARG>123456</CHARG><HSDAT>01.01.2011</HSDAT><VFDAT>01.01.2013</VFDAT><HSDAT_PRINT>01/2011</HSDAT_PRINT><VFDAT_PRINT>01/2013</VFDAT_PRINT><CHARGE_PRINT>HURRA</CHARGE_PRINT><DRUCK_INFO1>24,57 EURO</DRUCK_INFO1><DRUCK_INFO2>WARUM</DRUCK_INFO2><DRUCK_INFO3>NICHT</DRUCK_INFO3><CIP></CIP><GS1_BATCH></GS1_BATCH><GS1_HSDAT></GS1_HSDAT><GS1_VFDAT></GS1_VFDAT></I_ORDER_CREATE>"
				// +
				// "<I_ORDER_CREATE><ODERNR>DEMO_ORDER_B</ODERNR><ACTION>1</ACTION><RESSOURCE>DMT</RESSOURCE><LAYOUT>TEST</LAYOUT><MATNR>000000000000101702</MATNR></I_ORDER_CREATE>"
				+ "</INPUT><OUTPUT><E_RETURNCODE></E_RETURNCODE></OUTPUT></Z_PPFM_PCE_ORDER_CREATE>";

		try {
			List<Order> orderList = createOrderBean.getParsedOrderList(xml);
			if (orderList.isEmpty()) {
				FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "ABORTED", MessageFormat.format("Import order: {0} failed. Order already exist", "DEMO_ORDER_" + createDemoOrderInt));
				FacesContext.getCurrentInstance().addMessage(null, fm);
			}
			for (Order od : orderList) {
				FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, "ADDED", MessageFormat.format("Import order: {0} succeeded", od.getName()));
				FacesContext.getCurrentInstance().addMessage(null, fm);
			}
		} catch (Exception e) {
			FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "ABORTED", MessageFormat.format("Import order: {0} failed. {1}", "DEMO_ORDER_" + createDemoOrderInt, e.getMessage()));
			FacesContext.getCurrentInstance().addMessage(null, fm);
			e.printStackTrace();
		}
		if (createDemoOrderInt == 10) {
			createDemoOrderInt = 0;
		}else{
			createDemoOrderInt++;
		}
	}

	public void deleteDemoOrder(ActionEvent actionEvent) {
		String xml = "<Z_PPFM_PCE_ORDER_DELETE> <INPUT> <I_HEADER><ODERNR>DEMO_ORDER_" + deleteDemoOrderInt + "</ODERNR>" + "<ACTION>2</ACTION></I_HEADER></INPUT><OUTPUT> <E_RETURNCODE></E_RETURNCODE></OUTPUT></Z_PPFM_PCE_ORDER_DELETE>";

		try {
			Order order = deleteOrderBean.getParsedOrder(xml);
			if (order != null) {
				// try to merge
				String orderName = order.getName();
				Order updatedOrder = orderBean.updateOrder(order);

				if (updatedOrder.getStatus() > 1) {
					FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "ABORTED", MessageFormat.format("Can not delete order: {0} with status: {1}", orderName, order.getStatus()));
					FacesContext.getCurrentInstance().addMessage(null, fm);
				}else if (orderBean.removeOrder(updatedOrder)) {
					FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, "REMOVED", MessageFormat.format("Order: {0} deleted successfully", orderName));
					FacesContext.getCurrentInstance().addMessage(null, fm);
				}
			} else {
				FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "ABORTED", MessageFormat.format("Can not delete empty order {0}", deleteDemoOrderInt));
				FacesContext.getCurrentInstance().addMessage(null, fm);
			}
			if (deleteDemoOrderInt == 10) {
				deleteDemoOrderInt = 0;
			}else{
				deleteDemoOrderInt++;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void getDemoOrderStatus(ActionEvent actionEvent) {
		String xml = "<Z_PPFM_PCE_ORDER_STATUS_GET> <INPUT> <I_HEADER><ODERNR>DEMO_ORDER_" + statusDemoOrderInt + "</ODERNR> <ACTION>4</ACTION> </I_HEADER> </INPUT><OUTPUT> <E_RETURNCODE></E_RETURNCODE> </OUTPUT></Z_PPFM_PCE_ORDER_STATUS_GET>";
		try {
			Order order = statusOrderBean.getParsedOrder(xml);
			if (order != null) {
				// try to merge
				String orderName = order.getName();
				Order updatedOrder = orderBean.updateOrder(order);

				FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, "STATUS", MessageFormat.format("Order: {0} with status: {1}", orderName, updatedOrder.getStatus()));
				FacesContext.getCurrentInstance().addMessage(null, fm);
				
			} else {
				FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_WARN, "ABORTED", MessageFormat.format("Can not request empty order {0}", statusDemoOrderInt));
				FacesContext.getCurrentInstance().addMessage(null, fm);
			}
			if (statusDemoOrderInt == 10) {
				statusDemoOrderInt = 0;
			}else{
				statusDemoOrderInt++;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
